<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
        }
        .header {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .header h1 {
            color: #667eea;
            margin-bottom: 10px;
        }
        .header p {
            color: #666;
            margin: 5px 0;
        }
        .chat-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            display: flex;
            flex-direction: column;
            height: 600px;
        }
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .message {
            margin-bottom: 15px;
            animation: slideInUp 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            transform-origin: bottom;
        }
        @keyframes slideInUp {
            from { 
                opacity: 0; 
                transform: translateY(20px) scale(0.95); 
            }
            to { 
                opacity: 1; 
                transform: translateY(0) scale(1); 
            }
        }
        .message.streaming {
            animation: none;
            opacity: 1;
        }
        .message.user {
            display: flex;
            justify-content: flex-end;
        }
        .message.assistant {
            display: flex;
            justify-content: flex-start;
        }
        .message-content {
            max-width: 70%;
            padding: 12px 18px;
            border-radius: 18px;
            word-wrap: break-word;
        }
        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .message.assistant .message-content {
            background: white;
            color: #333;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .confirmation-panel {
            display: none;
            background: #fff3cd;
            border: 2px solid #ffc107;
            border-radius: 10px;
            padding: 20px;
            margin: 10px;
        }
        .confirmation-panel.active {
            display: block;
            animation: slideDown 0.3s;
        }
        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0.3; }
        }
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.1); opacity: 0.8; }
        }
        .typing-cursor {
            color: #667eea;
            font-weight: bold;
            margin-left: 2px;
            display: inline-block;
            animation: blink 1.2s infinite;
        }
        .typing-indicator {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 8px 12px;
            background: rgba(102, 126, 234, 0.1);
            border-radius: 12px;
            margin: 5px 0;
        }
        .typing-dot {
            width: 6px;
            height: 6px;
            background: #667eea;
            border-radius: 50%;
            animation: pulse 1.4s infinite;
        }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }
        .typing-dot:nth-child(4) { animation-delay: 0.6s; }
        .confirmation-tool {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
        }
        .tool-name {
            font-weight: bold;
            color: #dc3545;
            margin-bottom: 8px;
        }
        .tool-args {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            font-family: monospace;
            font-size: 14px;
        }
        .confirmation-buttons {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        .btn-approve {
            background: #28a745;
            color: white;
        }
        .btn-approve:hover {
            background: #218838;
        }
        .btn-reject {
            background: #dc3545;
            color: white;
        }
        .btn-reject:hover {
            background: #c82333;
        }
        .chat-input-container {
            padding: 20px;
            background: white;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 10px;
        }
        #messageInput {
            flex: 1;
            padding: 12px 18px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
        }
        #messageInput:focus {
            border-color: #667eea;
        }
        #sendButton {
            padding: 12px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
        }
        #sendButton:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        .status {
            text-align: center;
            padding: 10px;
            color: #666;
            font-size: 14px;
            transition: all 0.3s ease;
            min-height: 20px;
        }
        .status.active {
            background: rgba(102, 126, 234, 0.1);
            border-radius: 8px;
            color: #667eea;
            font-weight: 500;
        }
        .message-content {
            position: relative;
            overflow-wrap: break-word;
            word-break: break-word;
        }
        .message-content.typing {
            border-right: 2px solid #667eea;
            animation: typing-border 1s infinite;
        }
        @keyframes typing-border {
            0%, 50% { border-right-color: #667eea; }
            51%, 100% { border-right-color: transparent; }
        }
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
            20%, 40%, 60%, 80% { transform: translateX(5px); }
        }
        @keyframes buttonPulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        #sendButton:hover:not(:disabled) {
            animation: buttonPulse 0.3s ease;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        #messageInput:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            transform: translateY(-1px);
        }
        .version-info {
            background: rgba(255,255,255,0.1);
            padding: 10px;
            border-radius: 8px;
            margin-top: 10px;
        }
        .version-info small {
            color: #333;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 {{ app_name }} (支持流式响应)</h1>
            <p><strong>支持的操作：</strong></p>
            {% for operation in safe_operations %}
            <p>✅ {{ operation }}</p>
            {% endfor %}
            {% for operation in dangerous_operations %}
            <p>⚠️ {{ operation }}</p>
            {% endfor %}
            <p><strong>新功能：</strong>🚀 流式响应 - 实时显示 AI 回复过程</p>
            <p><strong>示例命令：</strong>{{ example_commands }}</p>
            
            <div class="version-info">
                <small>版本: {{ version }} | 构建时间: {{ build_time }}</small>
            </div>
        </div>

        <div class="chat-container">
            <div class="chat-messages" id="chatMessages">
                <div class="message assistant">
                    <div class="message-content">
                        {{ welcome_message }}
                    </div>
                </div>
            </div>
            
            <div class="confirmation-panel" id="confirmationPanel">
                <h3>⚠️ 需要确认以下操作</h3>
                <div id="toolsList"></div>
                <div class="confirmation-buttons">
                    <button class="btn btn-approve" onclick="confirmAll(true)">✓ 全部批准</button>
                    <button class="btn btn-reject" onclick="confirmAll(false)">✗ 全部拒绝</button>
                </div>
            </div>
            
            <div class="status" id="statusMessage"></div>
            
            <div class="chat-input-container">
                <input type="text" id="messageInput" placeholder="输入消息... (Enter发送, Ctrl+Enter快速发送, Esc清空)" />
                <label style="display: flex; align-items: center; gap: 5px; margin-right: 10px;">
                    <input type="checkbox" id="streamToggle" checked />
                    <span style="font-size: 14px;">流式响应</span>
                </label>
                <button type="button" id="sendButton">发送</button>
                {% if debug_mode %}
                <button type="button" id="testButton" onclick="testButtonClick()" style="margin-left: 10px; background: #dc3545; color: white; border: none; padding: 12px 20px; border-radius: 25px;">测试</button>
                {% endif %}
            </div>
        </div>
    </div>

    <script>
        let currentRunId = null;
        let pendingTools = [];
        let currentEventSource = null;
        let currentMessageElement = null;

        // 测试函数 - 验证按钮点击是否工作
        function testButtonClick() {
            console.log('Test button clicked!');
            alert('按钮点击测试成功！');
        }

        function addMessage(role, content, isStreaming = false) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}${isStreaming ? ' streaming' : ''}`;
            
            const messageContent = document.createElement('div');
            messageContent.className = 'message-content';
            messageContent.innerHTML = content;
            
            messageDiv.appendChild(messageContent);
            chatMessages.appendChild(messageDiv);
            
            // 平滑滚动到底部
            requestAnimationFrame(() => {
                chatMessages.scrollTo({
                    top: chatMessages.scrollHeight,
                    behavior: 'smooth'
                });
            });
            
            if (isStreaming) {
                currentMessageElement = messageContent;
                messageContent.classList.add('typing');
                // 添加打字指示器
                showTypingIndicator();
            }
            
            return messageDiv;
        }

        function updateCurrentMessage(content) {
            if (currentMessageElement) {
                currentMessageElement.innerHTML = content;
                document.getElementById('chatMessages').scrollTop = document.getElementById('chatMessages').scrollHeight;
            }
        }

        function appendToCurrentMessage(delta) {
            if (currentMessageElement && delta) {
                console.log('Appending delta:', delta);
                
                // 移除现有光标
                const existingCursor = currentMessageElement.querySelector('.typing-cursor');
                if (existingCursor) {
                    existingCursor.remove();
                }
                
                // 直接添加内容（简化版本，确保能看到效果）
                currentMessageElement.innerHTML += delta;
                
                // 添加光标效果
                const cursor = document.createElement('span');
                cursor.className = 'typing-cursor';
                cursor.innerHTML = '▋';
                currentMessageElement.appendChild(cursor);
                
                // 使用优化的滚动函数
                optimizedScroll();
            }
        }
        
        function finishTyping() {
            if (currentMessageElement) {
                // 移除光标和打字效果
                const cursor = currentMessageElement.querySelector('.typing-cursor');
                if (cursor) {
                    cursor.remove();
                }
                currentMessageElement.classList.remove('typing');
                hideTypingIndicator();
            }
        }

        function showTypingIndicator() {
            const statusElement = document.getElementById('statusMessage');
            if (!statusElement.querySelector('.typing-indicator')) {
                const indicator = document.createElement('div');
                indicator.className = 'typing-indicator';
                indicator.innerHTML = '<div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div>';
                statusElement.appendChild(indicator);
            }
        }

        function hideTypingIndicator() {
            const statusElement = document.getElementById('statusMessage');
            const indicator = statusElement.querySelector('.typing-indicator');
            if (indicator) {
                indicator.remove();
            }
        }

        function showStatus(message, isActive = false) {
            const statusElement = document.getElementById('statusMessage');
            statusElement.textContent = message;
            
            if (isActive) {
                statusElement.classList.add('active');
            } else {
                statusElement.classList.remove('active');
            }
            
            // 如果有消息，添加淡入效果
            if (message) {
                statusElement.style.opacity = '0';
                requestAnimationFrame(() => {
                    statusElement.style.transition = 'opacity 0.3s ease';
                    statusElement.style.opacity = '1';
                });
            }
        }

        function showConfirmationPanel(tools, runId) {
            currentRunId = runId;
            pendingTools = tools;
            
            const panel = document.getElementById('confirmationPanel');
            const toolsList = document.getElementById('toolsList');
            toolsList.innerHTML = '';
            
            tools.forEach((tool, index) => {
                const toolDiv = document.createElement('div');
                toolDiv.className = 'confirmation-tool';
                toolDiv.innerHTML = `
                    <div class="tool-name">🔧 ${tool.tool_name}</div>
                    <div class="tool-args">参数：${JSON.stringify(tool.tool_args, null, 2)}</div>
                    <div class="confirmation-buttons">
                        <button class="btn btn-approve" onclick="confirmTool(${index}, true)">✓ 批准</button>
                        <button class="btn btn-reject" onclick="confirmTool(${index}, false)">✗ 拒绝</button>
                    </div>
                `;
                toolsList.appendChild(toolDiv);
            });
            
            panel.classList.add('active');
            showStatus('等待用户确认操作...');
        }

        function hideConfirmationPanel() {
            document.getElementById('confirmationPanel').classList.remove('active');
            showStatus('');
        }

        function closeEventSource() {
            if (currentEventSource) {
                currentEventSource.close();
                currentEventSource = null;
            }
        }

        async function confirmTool(index, confirmed) {
            pendingTools[index].confirmed = confirmed;
            
            // 检查是否所有工具都已确认
            const allConfirmed = pendingTools.every(t => t.hasOwnProperty('confirmed'));
            
            if (allConfirmed) {
                await continueRun();
            }
        }

        async function confirmAll(confirmed) {
            pendingTools.forEach(tool => {
                tool.confirmed = confirmed;
            });
            await continueRun();
        }

        async function continueRunStream() {
            showStatus('继续执行...');
            hideConfirmationPanel();
            closeEventSource();
            
            try {
                // 创建流式请求
                console.log('Making fetch request to /api/continue/stream');
                const response = await fetch('/api/continue/stream', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        run_id: currentRunId,
                        tools: pendingTools
                    })
                });

                console.log('Continue response status:', response.status);
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('HTTP error response:', errorText);
                    throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
                }

                console.log('Starting to read continue stream');
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) {
                        console.log('Continue stream reading completed');
                        break;
                    }

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop(); // 保留不完整的行

                    for (const line of lines) {
                        if (line.trim() === '') continue; // 跳过空行
                        
                        if (line.startsWith('data: ')) {
                            try {
                                const jsonStr = line.slice(6);
                                console.log('Parsing continue JSON:', jsonStr);
                                const data = JSON.parse(jsonStr);
                                handleStreamEvent(data);
                            } catch (e) {
                                console.error('Error parsing continue SSE data:', e, 'Line:', line);
                            }
                        } else {
                            console.log('Non-data continue line:', line);
                        }
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                addMessage('assistant', '发生错误：' + error.message);
                showStatus('');
            }
        }

        function handleStreamEvent(data) {
            console.log('Received stream event:', data);
            switch (data.type) {
                case 'start':
                    console.log('Stream started');
                    showStatus(data.message || '开始处理...', true);
                    // 禁用发送按钮
                    document.getElementById('sendButton').disabled = true;
                    break;
                
                case 'content':
                    console.log('Received content:', data.content);
                    if (!currentMessageElement) {
                        addMessage('assistant', '', true);
                    }
                    // 使用优化的追加方式
                    appendToCurrentMessage(data.content);
                    showStatus('正在生成回复...', true);
                    break;
                
                case 'delta':
                    console.log('Received delta:', data.delta);
                    if (!currentMessageElement) {
                        console.log('Creating new assistant message for streaming');
                        addMessage('assistant', '', true);
                    }
                    // 直接使用即时添加，确保能看到效果
                    appendToCurrentMessageInstant(data.delta);
                    showStatus('正在生成回复...', true);
                    break;
                
                case 'event':
                    console.log('Received event:', data.event);
                    // 显示事件状态
                    if (data.event && data.event !== 'unknown') {
                        showStatus(`处理中: ${data.event}`, true);
                    }
                    break;
                
                case 'pause':
                    console.log('Stream paused for confirmation');
                    finishTyping();
                    currentMessageElement = null;
                    showConfirmationPanel(data.tools_requiring_confirmation, data.run_id);
                    // 重新启用发送按钮
                    document.getElementById('sendButton').disabled = false;
                    break;
                
                case 'complete':
                    console.log('Stream completed');
                    finishTyping();
                    currentMessageElement = null;
                    showStatus('');
                    // 重新启用发送按钮
                    document.getElementById('sendButton').disabled = false;
                    // 聚焦到输入框
                    document.getElementById('messageInput').focus();
                    break;
                
                case 'error':
                    console.error('Stream error:', data.error);
                    finishTyping();
                    currentMessageElement = null;
                    addMessage('assistant', `❌ 发生错误：${data.error}`);
                    showStatus('');
                    // 重新启用发送按钮
                    document.getElementById('sendButton').disabled = false;
                    break;
                    
                default:
                    console.log('Unknown event type:', data.type);
                    break;
            }
        }

        // 即时添加内容的函数，用于小的增量更新
        function appendToCurrentMessageInstant(delta) {
            if (currentMessageElement && delta) {
                // 移除现有光标
                const existingCursor = currentMessageElement.querySelector('.typing-cursor');
                if (existingCursor) {
                    existingCursor.remove();
                }
                
                // 直接添加内容
                currentMessageElement.innerHTML += delta;
                
                // 添加光标效果
                const cursor = document.createElement('span');
                cursor.className = 'typing-cursor';
                cursor.innerHTML = '▋';
                currentMessageElement.appendChild(cursor);
                
                // 使用优化的滚动函数
                optimizedScroll();
            }
        }

        async function sendMessageStream() {
            console.log('sendMessageStream called');
            const input = document.getElementById('messageInput');
            const sendButton = document.getElementById('sendButton');
            const message = input.value.trim();
            
            if (!message) {
                // 输入框抖动提示
                input.style.animation = 'shake 0.5s';
                setTimeout(() => input.style.animation = '', 500);
                return;
            }
            
            console.log('Sending message:', message);
            
            // 添加用户消息
            addMessage('user', message);
            input.value = '';
            
            // 禁用输入和按钮
            input.disabled = true;
            sendButton.disabled = true;
            sendButton.textContent = '发送中...';
            
            showStatus('正在发送消息...', true);
            closeEventSource();
            
            try {
                // 创建流式请求
                console.log('Making fetch request to /api/chat/stream');
                const response = await fetch('/api/chat/stream', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });

                console.log('Response status:', response.status);
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('HTTP error response:', errorText);
                    throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
                }

                console.log('Starting to read response stream');
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) {
                        console.log('Stream reading completed');
                        break;
                    }

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop(); // 保留不完整的行

                    for (const line of lines) {
                        if (line.trim() === '') continue; // 跳过空行
                        
                        if (line.startsWith('data: ')) {
                            try {
                                const jsonStr = line.slice(6);
                                console.log('Parsing JSON:', jsonStr);
                                const data = JSON.parse(jsonStr);
                                handleStreamEvent(data);
                            } catch (e) {
                                console.error('Error parsing SSE data:', e, 'Line:', line);
                            }
                        } else {
                            console.log('Non-data line:', line);
                        }
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                addMessage('assistant', `❌ 连接错误：${error.message}`);
                showStatus('');
            } finally {
                // 恢复输入和按钮状态
                input.disabled = false;
                sendButton.disabled = false;
                sendButton.textContent = '发送';
                input.focus();
            }
        }

        // 为了向后兼容，保留非流式版本
        async function sendMessage() {
            console.log('sendMessage (non-stream) called');
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (!message) return;
            
            console.log('Sending message (non-stream):', message);
            addMessage('user', message);
            input.value = '';
            showStatus('处理中...');
            
            try {
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });
                
                const data = await response.json();
                
                if (data.is_paused && data.tools_requiring_confirmation) {
                    showConfirmationPanel(data.tools_requiring_confirmation, data.run_id);
                } else {
                    if (data.response) {
                        addMessage('assistant', data.response);
                    }
                    showStatus('');
                }
            } catch (error) {
                console.error('Error:', error);
                addMessage('assistant', '发生错误：' + error.message);
                showStatus('');
            }
        }

        // 根据切换按钮选择使用流式或非流式版本
        function handleSendMessage() {
            console.log('handleSendMessage called');
            const isStreamEnabled = document.getElementById('streamToggle').checked;
            console.log('Stream enabled:', isStreamEnabled);
            if (isStreamEnabled) {
                sendMessageStream();
            } else {
                sendMessage();
            }
        }

        async function continueRun() {
            const isStreamEnabled = document.getElementById('streamToggle').checked;
            if (isStreamEnabled) {
                await continueRunStream();
            } else {
                await continueRunNonStream();
            }
        }

        async function continueRunNonStream() {
            showStatus('继续执行...');
            hideConfirmationPanel();
            
            try {
                const response = await fetch('/api/continue', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        run_id: currentRunId,
                        tools: pendingTools
                    })
                });
                
                const data = await response.json();
                
                if (data.response) {
                    addMessage('assistant', data.response);
                }
                
                if (data.is_paused && data.tools_requiring_confirmation) {
                    showConfirmationPanel(data.tools_requiring_confirmation, data.run_id);
                } else {
                    showStatus('');
                }
            } catch (error) {
                console.error('Error:', error);
                addMessage('assistant', '发生错误：' + error.message);
                showStatus('');
            }
        }

        // 性能优化：使用节流函数
        function throttle(func, limit) {
            let inThrottle;
            return function() {
                const args = arguments;
                const context = this;
                if (!inThrottle) {
                    func.apply(context, args);
                    inThrottle = true;
                    setTimeout(() => inThrottle = false, limit);
                }
            }
        }

        // 防抖函数，用于优化滚动性能
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }

        // 优化的滚动函数
        const optimizedScroll = debounce(() => {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTo({
                top: chatMessages.scrollHeight,
                behavior: 'smooth'
            });
        }, 100);

        // 确保DOM完全加载后再绑定事件
        function initializeEventListeners() {
            console.log('Initializing event listeners...');
            const sendButton = document.getElementById('sendButton');
            const messageInput = document.getElementById('messageInput');
            const streamToggle = document.getElementById('streamToggle');
            
            console.log('Send button found:', sendButton);
            console.log('Message input found:', messageInput);
            console.log('Stream toggle found:', streamToggle);
            
            if (sendButton) {
                // 使用节流优化按钮点击
                const throttledSend = throttle(handleSendMessage, 1000);
                sendButton.addEventListener('click', function(e) {
                    console.log('Send button clicked!');
                    e.preventDefault();
                    if (!sendButton.disabled) {
                        throttledSend();
                    }
                });
                console.log('Send button event listener added');
            } else {
                console.error('Send button not found!');
            }
            
            if (messageInput) {
                // 优化输入框事件
                messageInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        console.log('Enter key pressed, calling handleSendMessage');
                        e.preventDefault();
                        if (!document.getElementById('sendButton').disabled) {
                            handleSendMessage();
                        }
                    }
                });
                
                // 添加输入提示
                messageInput.addEventListener('input', debounce((e) => {
                    const value = e.target.value.trim();
                    const sendButton = document.getElementById('sendButton');
                    if (value) {
                        sendButton.style.opacity = '1';
                        sendButton.style.transform = 'scale(1)';
                    } else {
                        sendButton.style.opacity = '0.7';
                        sendButton.style.transform = 'scale(0.95)';
                    }
                }, 150));
                
                console.log('Message input event listener added');
            } else {
                console.error('Message input not found!');
            }
            
            // 添加键盘快捷键支持
            document.addEventListener('keydown', (e) => {
                // Ctrl/Cmd + Enter 快速发送
                if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                    e.preventDefault();
                    if (!document.getElementById('sendButton').disabled) {
                        handleSendMessage();
                    }
                }
                // Escape 键清空输入
                if (e.key === 'Escape') {
                    messageInput.value = '';
                    messageInput.focus();
                }
            });
        }

        // 页面加载优化
        function initializePage() {
            initializeEventListeners();
            
            // 预加载和优化
            const messageInput = document.getElementById('messageInput');
            const sendButton = document.getElementById('sendButton');
            
            // 设置初始状态
            if (messageInput) {
                messageInput.focus();
                // 初始化发送按钮状态
                sendButton.style.opacity = '0.7';
                sendButton.style.transform = 'scale(0.95)';
                sendButton.style.transition = 'all 0.3s ease';
            }
            
            // 添加页面可见性变化监听
            document.addEventListener('visibilitychange', () => {
                if (!document.hidden && messageInput) {
                    // 页面重新可见时聚焦输入框
                    setTimeout(() => messageInput.focus(), 100);
                }
            });
            
            console.log('Page initialized successfully');
        }

        // 当DOM加载完成时初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initializePage);
        } else {
            // DOM已经加载完成
            initializePage();
        }
    </script>
</body>
</html>
